<?php

namespace App\Admin\Controllers;

use App\Admin\Repositories\CardsBatch;
use App\Server\CardsServer;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Show;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Carbon;

class CardsBatchController extends AdminController
{
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        return Grid::make(new CardsBatch(), function (Grid $grid) {
            $grid->column('id')->sortable();
            $grid->column('card_batch_name');
            $grid->column('brand_id');
            $grid->column('num');
            $grid->column('created_at');
            $grid->column('updated_at')->sortable();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->equal('id');

            });
        });
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     *
     * @return Show
     */
    protected function detail($id)
    {
        return Show::make($id, new CardsBatch(), function (Show $show) {
            $show->field('id');
            $show->field('card_batch_name');
            $show->field('brand_id');
            $show->field('num');
            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        return Form::make(new CardsBatch(), function (Form $form) {
            $form->display('id');
            $form->text('card_batch_name')->help('标记用');

            $form->select('brand_id')->options(function ($id) {

            })
                ->load('product_id', 'product/get')
                ->ajax('brands/get');

            $form->select('product_id', '所属产品');

            $form->text('num')->help('最大值为999999');

            // 有效期
            $form->radio('validity_time', '有效期')->options([
                12 => '12个月',
                18 => '18个月',
                24 => '24个月',
            ])->default(12);

            $form->display('created_at');
            $form->display('updated_at');

            // 保存前回调
            $form->saving(function (Form $form) {
                // 构建批次标识
                $form->batch_no = date('YmdHis') . random_int(10000, 99999);
            });

            // 保存后，触发队列，生成具体的质保卡
            $form->saved(function (Form $form, $result) {
                // 此时表示新增成功
                if ($form->isCreating() && $result > 0) {
                    // 根据生成个数，调用服务创建具体的质保卡
                    (new CardsServer())->buildQueueData($form->brand_id, $result, $form->num);
                }
            });
        });
    }
}
